package com.example.java_websocket.web.websocket;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.java_websocket.model.ChatHistory1;
import com.example.java_websocket.model.User;
import com.example.java_websocket.service.IChatHistoryService;
import com.example.java_websocket.service.IMessageRankService;
import com.example.java_websocket.service.IOnlineUserService;
import com.example.java_websocket.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
@ServerEndpoint(value = "/chat/{userId}")
@Slf4j
public class ChatEndpoint {
    // session缓存
    final static Map<String, Session> sessionMap = new HashMap<>();
//    websocket无法注入bean对象
    public ChatEndpoint (){
        System.out.println("载入 ChatEndpoint 构造方法");
    }
//    private static ChatHistoryMapper chatHistoryMapper;
//    //static:静态字段，这意味着它在整个 ChatEndpoint 类中是共享的。
//    @Autowired
//    public  void setChatHistoryMapper(ChatHistoryMapper chatHistoryMapper) {
//        ChatEndpoint.chatHistoryMapper = chatHistoryMapper;
//    }

//    private static ApplicationContext applicationContext;
//    @Autowired
//    public void setApplicationContext(ApplicationContext applicationContext) {
//        ChatEndpoint.applicationContext = applicationContext;
//    }

    private static IOnlineUserService onlineUserService;
    private static  IMessageRankService messageRankService;
    private static  MessageBroadcaster broadcaster;
//    private static ObjectMapper objectMapper;
    private static IChatHistoryService chatHistoryService;
    private static IUserService userService;

    @Autowired
    public void setServices(IOnlineUserService ous, IMessageRankService mrs,
                            MessageBroadcaster mb, IChatHistoryService cs,IUserService us) {
        onlineUserService = ous;
        messageRankService = mrs;
        broadcaster = mb;
        chatHistoryService = cs;
        userService = us;
    }
    @OnOpen
    public void onOpen(Session session, @PathParam("userId")String userId) throws IOException {
        System.out.println("连接建立: " + session.getId());
        User detail = userService.detail(userId);
//        String userId = extractUserId(session);
//        System.out.println("===========");
//        System.out.println(userId);
//        if (userId != null) {
//            onlineUserService.userLogin(userId);
//            sendOnlineUsersUpdate();
//        }
        // 判断用户是否合法
        if (detail == null){
            deClose(session,"用户id不存在, 拒绝连接");
            return;
        }
        // redis记录在线用户
        onlineUserService.userLogin(userId);
        sessionMap.put(session.getId(), session);
    }

    /**
     * 向ws chat客户端发送错误消息,并且断开连接
     * @param session session会话
     * @param msg 错误消息
     */
    private void deClose(Session session, String msg) throws IOException {
        try {
            if (StrUtil.isNotBlank(msg)){
                sendMessage(session,msg);
            }
            session.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 发送文本消息
     *
     * @param session ws会话对象
     * @param msg     消息文本
     */
    private void sendMessage(Session session, String msg) throws IOException {
        try {
            session.getBasicRemote().sendText(msg);
        } catch (IOException e) {
        log.info("给 ws 客户端: {} 发送消息失败",session.getId());
        }
    }


    @OnMessage
    public void onMessage(String msg, Session session,@PathParam("userId") String userId){
//        try {
//
//            if (chatHistoryMapper != null) {
//                // 持久化消息到数据库
//                chatHistoryMapper.insert(message);
//                System.out.println("消息存储成功");
//            } else {
//                System.err.println("chatHistoryMapper 未正确注入");
//            }
//            // 广播消息给所有客户端
//            for (Session s : session.getOpenSessions()) {
//                s.getBasicRemote().sendText(message);
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        String userId = extractUserId(session);
//
//        // 存储到MySQL
//        chatHistoryDAO.saveMessage(message);
//        // 更新消息排行榜
//        messageRankService.incrementMessageCount(userId);
//        // 通过Redis广播消息
//        broadcaster.broadcast(message);

//        String userId = extractUserId(session);
//        System.out.println("--------------------------");
//        System.out.println(userId);
        if (session.isOpen()){
            System.out.println("收到ws消息 = " + msg);
            // 记录消息排行信息
            messageRankService.incrementMessageCount(userId);
            // 通过Redis广播消息
            broadcaster.publishMessage(msg);
            // 解析用户发送过来的json格式消息内容
            // 如果用户发送了非json数据,会导致异常.
            try {
                JSONObject jsonObject = JSONUtil.parseObj(msg);
                ChatHistory1 chatHistory = jsonObject.toBean(ChatHistory1.class);
                chatHistoryService.add(chatHistory);
            }catch (Exception e){
                //
                System.err.println("解析json格式异常, json:"+msg);
            }
        }
//        if (userId != null) {
//            ChatHistory1 chatHistory1 = objectMapper.readValue(message, ChatHistory1.class);
//            // 存储到MySQL
////            chatHistoryMapper.insert(message);
//            chatHistoryService.add(chatHistory1);
//            System.out.println("消息存储成功");
//            // 更新消息排行榜
//            messageRankService.incrementMessageCount(userId);
//
//        }
    }
    @OnClose
    public void onClose(Session session,CloseReason reason) {

        String sessionId = session.getId();
        String reasonPhrase = reason.getReasonPhrase();
        System.out.println(String.format("关闭ws连接: %s, reason: %s", sessionId, reasonPhrase));
        sessionMap.remove(sessionId);
    }
//    private String extractUserId(Session session) {
//        if (session == null) {
//            return null;
//        }
//        // 从会话属性中获取用户 ID
//        return (String) session.getAttributes().get("userId");
//    }
//    private String extractUserId(Session session) {
//        if (session == null) {
//            return null;
//        }
//        // 从会话属性中获取用户 ID
//        String[] strings = session.getRequestURI().getQuery().split("=");
//        return  strings[strings.length-1];
//    }
//
//    private void sendOnlineUsersUpdate() {
//        Set<String> users = onlineUserService.getOnlineUsers();
//        broadcaster.broadcast("ONLINE_USERS:" + String.join(",", users));
//    }
    @OnError
    public void onError(Session session,Throwable throwable) {
        System.out.println("发生错误: " + session.getId());
    }
}


